var bodyParser = require('body-parser');
var cheerio = require('cheerio');
var express = require('express');
var mysql = require('mysql');
var superagent = require('superagent');

var mysqlConfig = require('./config').mysqlConfig;

var list1 = [];
var connection1 = mysql.createConnection(mysqlConfig);
connection1.connect();
var query1 = 'select * from follow_list';
connection1.query(query1, function (err, res) {
    if (err) {
        console.log('err');
        console.log(err);
    } else {
        console.log('res');
        // console.log(res);
        list1 = res;
        update();
    }
});
connection1.end();

function update() {
    list1.forEach((v, i) => {
        var fundId = v['fund_id'];
        var initPrice = v['init_price'];


        var url = `http://fundgz.1234567.com.cn/js/${fundId}.js`
        console.log(url);
        superagent.get(url).end(function (err, res) {
            if (err) {
                console.log('err');

            } else {
                res.setEncoding('utf8');

                var str = res.body.toString();
                var str2 = str.replace(/jsonpgz./g, '').replace(/}../g, '}');

                var obj = JSON.parse(str2);

                var gz_gztime = obj.gztime;
                var gz_gsz = obj.gsz;
                var gz_gszzl = obj.gszzl;

                var query2 = `update follow_list set gs_time='${gz_gztime}',gsz=${gz_gsz}, gszf='${gz_gszzl}' where fund_id=${fundId}`;
                var connection2 = mysql.createConnection(mysqlConfig);
                connection2.connect();
                connection2.query(query2, function (err, res) {
                    if (err) {
                        console.log('err');
                        // console.log(err);

                    } else {
                        console.log('res');
                        console.log(res);

                    }
                });
                connection2.end();
            }
        })

        
    })

    setTimeout(() => {
        update();
    }, 60*1000);
}